package org.phalanx.server.game;

import java.util.ArrayList;
import java.util.Iterator;

import org.phalanx.messenging.AbstractMessage;
import org.phalanx.server.PhalanxServer;
import org.phalanx.server.ServerCache.CacheManager;
import org.phalanx.server.user.PhalanxUser;

public class JoinFeedMessage extends AbstractMessage {
	private ArrayList<PhalanxGamePlayer> players;

	public JoinFeedMessage(){
		super.setMessageHeader("joinfeed");
		players = new ArrayList<PhalanxGamePlayer>();
	}

	public void setGameName(String gameName){
		this.setToMessage("gamename", gameName);
	}

	public void setGameId(Integer gameId){
		if (gameId != null){
			this.setToMessage("gameid", gameId.toString());
		}
	}

	public void setMapId(String mapId){
		this.setToMessage("mapid", mapId);
	}

	public void setGameOwner(String gameOwner){
		this.setToMessage("owner", gameOwner);
	}

	public void setPhalanxPlayerInfo(PhalanxGamePlayer aPlayer){
		if (!players.contains(aPlayer)){
			players.add(aPlayer);
			serializePhalanxPlayersList();
		}
	}

	private void serializePhalanxPlayersList(){
		Iterator<PhalanxGamePlayer> i = players.iterator();
		StringBuffer serializedPlayers = new StringBuffer();
		boolean isFirst = true;


		while (i.hasNext()){
			PhalanxGamePlayer onePlayer = i.next();

			CacheManager cacheMgr = PhalanxServer.getServerInstance().getCacheManager();

			PhalanxUser u = (PhalanxUser)cacheMgr.getElement("UserCache", onePlayer.getUserId());

			if (u != null){
				if (isFirst){
					isFirst = false;
				} else {
					serializedPlayers.append(":");
				}

				serializedPlayers.append("{");
				serializedPlayers.append(onePlayer.getGameAlias());
				serializedPlayers.append("!");
				serializedPlayers.append(u.getUserName());
				serializedPlayers.append("!");
				serializedPlayers.append(u.getId());
				serializedPlayers.append("!");
				serializedPlayers.append(onePlayer.getTeamColor());
				serializedPlayers.append("!");
				serializedPlayers.append(onePlayer.getBuildPoint().getX());
				serializedPlayers.append("!");
				serializedPlayers.append(onePlayer.getBuildPoint().getY());
				serializedPlayers.append("}");
			}
		}
		
		this.setToMessage("players", serializedPlayers.toString());
	}
}
